import React, { useEffect, useState } from 'react'
import style from './style.module.scss'
import $ from 'jquery'
import { faMapMarker } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { UserService } from '../../../transfer/service/UserService'
import { message, Popconfirm } from 'antd'
import { PictureService } from '../../../transfer/service/PictureService'
import { CamerasService } from '../../../transfer/service/CamerasSerivce'
import { pushItem, replaceItemAtIndex } from '../../../utils/RecoilFunctions'
import { CloseOutlined } from '@ant-design/icons'
import { SearchService } from '../../../transfer/service/SearchService'
import { TagsService } from '../../../transfer/service/TagsService'

interface IEditPhotoCardProps {
    data: any
    imgId: string
}

export default function EditPhotoCard(props: IEditPhotoCardProps) {
    const [activeKey, setActiveKey] = useState(1)
    const [itemWidth, setItemWidth] = useState<any>()
    const [desc, setDesc] = useState<any>()
    const [location, setLocation] = useState<any>()
    const [tag, setTag] = useState<any>()
    const [tags, setTags] = useState<any>()
    const [tagList, setTagList] = useState<any>([])
    const [maker, setMaker] = useState<any>()
    const [model, setModel] = useState<any>()
    const [cameraId, setCameraId] = useState<string>()
    const [focalLength, setFocalLength] = useState<any>()
    const [aperture, setAperture] = useState<any>()
    const [iso, setIso] = useState<any>()
    const [allow, setAllow] = useState<boolean>(false)

    // 初始化布局
    useEffect(() => {
        setItemWidth($(`.${style.content}`).width() + 'px')
        setDesc(props.data.intro)
        setLocation(props.data.location)
        setTagList(props.data.tags)
        setMaker(props.data.camera.maker)
        setModel(props.data.camera.model)
        setCameraId(props.data.camera.id)
        setFocalLength(props.data.focalLength)
        setAperture(props.data.aperture)
        setIso(props.data.iso)
    }, [])

    // 删除点击事件
    const handleDelClick = () => {
        new UserService()
            .deletePictures(JSON.parse(localStorage.getItem('account') as any).id, props.imgId)
            .then(res => {
                message.info('删除成功')
            })
    }

    // 修改图片信息
    const handleUpdateClick = () => {
        if (maker == props.data.camera.maker && model == props.data.camera.model) {
            new UserService().updatePicture(
                JSON.parse(localStorage.getItem('account') as any).id,
                {
                    id: props.imgId,
                    userId: JSON.parse(localStorage.getItem('account') as any).id,
                    cameraId: cameraId,
                    width: props.data.width,
                    height: props.data.height,
                    imageUrl: props.data.imgUrl,
                    intro: desc,
                    focalLength: focalLength,
                    aperture: aperture,
                    iso: iso,
                    hash: props.data.hash,
                    createTime: '2021-02-17T20:52:51.2363138',
                    tags: tags,
                    topics: [
                        {
                            topicId: props.data.topics[0].id
                        }
                    ]
                },
                props.imgId
            )
        } else if (maker != props.data.camera.maker || model != props.data.camera.model) {
            new CamerasService().getCamera(maker).then(res => {
                res.data.data.map((camera: any) => {
                    if (camera.model == model) {
                        new UserService().updatePicture(
                            JSON.parse(localStorage.getItem('account') as any).id,
                            {
                                id: props.imgId,
                                userId: JSON.parse(localStorage.getItem('account') as any).id,
                                cameraId: camera.data.data.id,
                                width: props.data.width,
                                height: props.data.height,
                                imageUrl: props.data.imgUrl,
                                intro: desc,
                                focalLength: focalLength,
                                aperture: aperture,
                                iso: iso,
                                hash: props.data.hash,
                                createTime: '2021-02-17T20:52:51.2363138',
                                tags: tags,
                                topics: [
                                    {
                                        topicId: props.data.topics[0].id
                                    }
                                ]
                            },
                            props.imgId
                        )
                    } else {
                        new CamerasService()
                            .createCameras({
                                maker: maker,
                                model: model
                            })
                            .then(newCamera => {
                                new UserService().updatePicture(
                                    JSON.parse(localStorage.getItem('account') as any).id,
                                    {
                                        id: props.imgId,
                                        userId: JSON.parse(localStorage.getItem('account') as any).id,
                                        cameraId: newCamera.data.data.id,
                                        width: props.data.width,
                                        height: props.data.height,
                                        imageUrl: props.data.imgUrl,
                                        intro: desc,
                                        focalLength: focalLength,
                                        aperture: aperture,
                                        iso: iso,
                                        hash: props.data.hash,
                                        createTime: '2021-02-17T20:52:51.2363138',
                                        tags: tags,
                                        topics: [
                                            {
                                                topicId: props.data.topics[0].id
                                            }
                                        ]
                                    },
                                    props.imgId
                                )
                            })
                    }
                })
            })
        }
    }

    const handleTags = (e: any) => {
        if (e.key == 'Enter') {
            if (tag != '') {
                new SearchService().get('tags', tag, 0, 1).then(res => {
                    if (res.data.data.length != 0 && res.data.data[0].title != tag) {
                        setTagList(pushItem(tagList, { title: tag }))
                        setTags(pushItem(tags, { tagId: res.data.data[0].id }))
                    } else {
                        new TagsService().createTags({ title: tag }).then(res => {
                            setTagList(pushItem(tagList, { title: tag }))
                            setTags(pushItem(tags, { tagId: res.data.data.id }))
                        })
                    }
                })
            }
            setTags('')
        }
    }

    return (
        <div
            className={style.container}
            style={{
                ['--item-width' as any]: itemWidth
            }}>
            <div className={style.tab__container}>
                <div
                    className={`${style.tab__item} ${activeKey == 1 ? 'active' : ''}`}
                    onClick={() => {
                        setActiveKey(1)
                    }}>
                    <span>详情</span>
                </div>
                <div
                    className={`${style.tab__item} ${activeKey == 2 ? 'active' : ''}`}
                    onClick={() => {
                        setActiveKey(2)
                    }}>
                    <span>标签</span>
                </div>
                <div
                    className={`${style.tab__item} ${activeKey == 3 ? 'active' : ''}`}
                    onClick={() => {
                        setActiveKey(3)
                    }}>
                    <span>图像信息</span>
                </div>
                <div
                    className={`${style.tab__item} ${activeKey == 4 ? 'active' : ''}`}
                    onClick={() => {
                        setActiveKey(4)
                    }}>
                    <span>删除</span>
                </div>
            </div>
            <div className={style.content}>
                <div className={`${style.item} ${activeKey == 1 ? 'in' : 'leave'}`}>
                    <div className={style.item__input}>
                        <span>描述</span>
                        <textarea
                            value={desc}
                            onChange={e => {
                                setDesc(e.target.value)
                                setAllow(true)
                            }}
                            maxLength={600}
                            placeholder={'好的描述使照片更容易被发现。'}
                            rows={6}
                        />
                    </div>
                    <div className={style.item__input}>
                        <span>位置</span>
                        <div className={style.input}>
                            <FontAwesomeIcon icon={faMapMarker} className={style.icon} />
                            <input
                                value={location}
                                onChange={e => {
                                    setLocation(e.target.value)
                                    setAllow(true)
                                }}
                                type="text"
                                placeholder={'添加一个地方或城市'}
                            />
                        </div>
                    </div>
                </div>
                <div className={`${style.item} ${activeKey == 2 ? 'in' : 'leave'}`}>
                    <div className={style.item__input}>
                        <span>标签</span>
                        <div className={style.tags}>
                            {tagList.map((item: any, index: number) => {
                                return (
                                    <div className={style.tags__item} key={index}>
                                        <span>{item.title}</span>
                                        <CloseOutlined />
                                    </div>
                                )
                            })}
                            <input
                                value={tag}
                                onChange={e => {
                                    setTag(e.target.value)
                                    setAllow(true)
                                }}
                                onKeyDown={e => {
                                    handleTags(e)
                                }}
                                type="text"
                                placeholder={'输入标签，每输入完一个标签按回车键'}
                            />
                        </div>
                    </div>
                </div>
                <div className={`${style.item} ${activeKey == 3 ? 'in' : 'leave'}`}>
                    <div className={style.camera__item}>
                        <div className={style.camera__input}>
                            <span>照相机品牌</span>
                            <input
                                value={maker}
                                onChange={e => {
                                    setMaker(e.target.value)
                                    setAllow(true)
                                }}
                                type="text"
                                placeholder={'佳能'}
                            />
                        </div>
                        <div className={style.camera__input}>
                            <span>摄像机型号</span>
                            <input
                                value={model}
                                onChange={e => {
                                    setModel(e.target.value)
                                    setAllow(true)
                                }}
                                type="text"
                                placeholder={'佳能 EOS 7D'}
                            />
                        </div>
                    </div>
                    <div className={style.camera__item}>
                        <div className={style.camera__input}>
                            <span>焦距(mm)</span>
                            <input
                                value={focalLength}
                                onChange={e => {
                                    setFocalLength(e.target.value)
                                    setAllow(true)
                                }}
                                type="text"
                                placeholder={'60.0'}
                            />
                        </div>
                        <div className={style.camera__input}>
                            <span>光圈(ƒ)</span>
                            <input
                                value={aperture}
                                onChange={e => {
                                    setAperture(e.target.value)
                                    setAllow(true)
                                }}
                                type="text"
                                placeholder={'9.0'}
                            />
                        </div>
                    </div>
                    <div className={style.camera__item}>
                        <div className={style.camera__input}>
                            <span>ISO</span>
                            <input
                                value={iso}
                                onChange={e => {
                                    setIso(e.target.value)
                                    setAllow(true)
                                }}
                                type="text"
                                placeholder={'100'}
                            />
                        </div>
                    </div>
                </div>
                <div className={`${style.item} ${activeKey == 4 ? 'in' : 'leave'}`}>
                    <div className={style.delete__item}>
                        <p>删除照片</p>
                        <span>
                            从LineView中删除照片后，我们将尽一切努力防止其进一步散布，包括防止通过LineView查看和下载该照片。
                            但是，LineView许可证是不可撤销的，因此仍可以使用在删除之前下载的照片副本。
                        </span>
                        <Popconfirm
                            placement={'bottomLeft'}
                            title={'是否删除图片？'}
                            onConfirm={handleDelClick}
                            okText={'确定'}
                            cancelText={'取消'}>
                            <span className={style.del__btn}>我想删除这张照片</span>
                        </Popconfirm>
                    </div>
                </div>
            </div>

            <div className={style.bottom__btn}>
                <div className={style.cancel__btn}>取消</div>
                <div className={`${style.update__btn} ${allow ? 'allow' : ''}`} onClick={handleUpdateClick}>
                    上传
                </div>
            </div>
        </div>
    )
}
